package com.jinly.ryder.ssh.command;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.Session;
import com.jinly.ryder.common.error.SystemErrorType;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;

@Slf4j
public class SshCopyIdCommand {
    private Session sshSession;

    public SshCopyIdCommand(Session sshSession) {
        this.sshSession = sshSession;
    }

    public void exec(String pubKey) {
        ChannelExec channelExec = null;
        BufferedReader reader = null;
        String command = "echo '" + pubKey + "'>>~/.ssh/authorized_keys";
        try {
            channelExec = (ChannelExec) sshSession.openChannel("exec");
            channelExec.setCommand(command);
            channelExec.connect();
        } catch (Exception e) {
            log.error("ssh SshCopyId  err:{}", e.getMessage());
            SystemErrorType.INTERNAL_SERVER_ERROR.throwError("ssh命令执行失败");
        } finally {
            try {
                if (reader != null) reader.close();
                if (channelExec != null) channelExec.disconnect();
            } catch (Exception e) {
            }
        }
    }
}

